<template>
  <t-dialog
    v-model:visible="visible"
    :header="dialogTitle"
    width="600"
    :confirm-btn="{ loading }"
    @confirm="dialogConfirm"
    @close="dialogHide"
  >
    <t-space direction="vertical" style="width: 100%">
      <t-form ref="form" reset-type="initial" :data="formData" :rules="FORM_RULES" label-align="top">
        <t-row :gutter="[16, 24]">
          <t-col :span="6">
            <t-form-item :label="t('pages.dict.name')" name="name">
              <t-input v-model="formData.name" maxlength="16" show-limit-number />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.dict.mark')" name="type">
              <t-input v-model="formData.type" maxlength="16" show-limit-number />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item :label="t('pages.dict.remark')" name="remark">
              <t-textarea
                v-model="formData.remark"
                :autosize="{ minRows: 3, maxRows: 6 }"
                resize="none"
                show-limit-number
                maxlength="256"
              />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item :label="t('pages.dict.display')" name="display">
              <t-switch v-model="formData.display" :custom-value="[1, 0]" />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </t-space>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';

import { t } from '@/locales';

import { FORM_DATA, FORM_RULES, FormItem } from '../constants';

const loading = ref(false);
const emits = defineEmits(['confirm']);

const dialogTitle = ref('');
const type = ref('add');
const visible = ref(false);
const form = ref(null);
const formData = ref({ ...FORM_DATA });

const dialogShow = (action: string, row: FormItem) => {
  visible.value = true;
  type.value = action;
  if (action === 'edit') {
    formData.value = JSON.parse(JSON.stringify(row));
    dialogTitle.value = `${t('common.edit')}【${row.name}】`;
  } else {
    dialogTitle.value = t('common.add');
  }
};
const dialogHide = () => {
  form.value.reset();
  loading.value = false;
  visible.value = false;
};
const dialogConfirm = async () => {
  const valid = await form.value.validate();
  if (valid !== true) {
    return;
  }
  loading.value = true;
  emits('confirm', type.value, formData.value);
};
const loadingClear = () => {
  loading.value = false;
};

defineExpose({
  dialogShow,
  dialogHide,
  loadingClear,
});
</script>
